import { PageContainer } from '@ant-design/pro-components';
import { useRequest, history } from '@umijs/max';
import { Button, Card, List, Typography,  Modal, message } from 'antd';
import { Suspense, useEffect, useState, useRef } from 'react';
import type { CardListItemDataType } from './data.d.ts';
import {
  queryShotsList, delShortItem, addShortItem,
  editShortItem, querySummary, lockShortItem, queryLockShortItem,
  delockShortItem
} from './service';
import { useLocation } from 'umi';
import useStyles from './style.style';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import PageLoading from './components/PageLoading';
import IntroduceRow from './components/IntroduceRow';
import OperationModal from './components/OperationModal';

const { Paragraph } = Typography;

const CardList = () => {
  const { styles } = useStyles();
  const location = useLocation();
  const [open, setVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<any>(null);

  const searchParams = new URLSearchParams(location?.search)
  const id = searchParams.get('id')

  const { data = [], loading, run } = useRequest(queryShotsList, {
    manual: true,
  })

  const { data: summaryData, loading: summaryLoading, run: summaryRun } = useRequest(querySummary, {
    manual: true,
  });

  const init = () => {
    if (!id) {
      history.push('/dashboard')
      return
    }
    run({ project_id: id });
    summaryRun();
  }

  useEffect(() => {
    init()
  }, [])

  const { run: delItem } = useRequest(delShortItem, {
    manual: true,
    onSuccess: (data, params) => {
      // 删除 接口成功
      run({ project_id: id });
    },
  });

  const { run: addItem } = useRequest(addShortItem, {
    manual: true,
    onSuccess: (data, params) => {
      // add 接口成功
      setVisible(false);
      run({ project_id: id });
    },
  });

  const { run: editItem } = useRequest(editShortItem, {
    manual: true,
  });

  const { run: getLockitem } = useRequest(queryLockShortItem, {
    manual: true,
  });

  const { run: lockitem } = useRequest(lockShortItem, {
    manual: true
  });

  // 定时续锁与卸载处理
  const lockTimeoutRef = useRef<any>(null);
  const lastLockAtRef = useRef<number>(0);
  const hasUnlockedRef = useRef<boolean>(false);

  useEffect(() => {
    // 当编辑弹窗打开时，添加刷新/关闭页面时解锁，以及开启续锁定时器
    if (open && current?.id) {
      hasUnlockedRef.current = false;

      // 续锁：当当前数据的 duration（秒）耗尽时，触发一次加锁，然后再次排队
      const scheduleRenew = () => {
        const durationSec = Number(1000 * 60 * 5) || 0;
        const durationMs = Math.max(0, durationSec) * 1000;
        if (lockTimeoutRef.current) {
          clearTimeout(lockTimeoutRef.current);
        }
        lockTimeoutRef.current = setTimeout(() => {
          lockitem({ id: current.id, lock_duration_minutes: 1 });
          lastLockAtRef.current = Date.now();
          scheduleRenew();
        }, durationMs);
      };
      lastLockAtRef.current = Date.now();
      scheduleRenew();

      // 刷新/关闭页面时解锁（尽最大努力）
      const beforeUnloadHandler = () => {
        try {
          const token = localStorage.getItem('token');
          // 使用 keepalive 以便在页面卸载时也能发起请求
          fetch(`/api/shots/${current.id}/lock`, {
            method: 'DELETE',
            keepalive: true,
            headers: token ? { Authorization: `Bearer ${token}` } : undefined,
          }).catch(() => {});
          hasUnlockedRef.current = true;
        } catch (_) {
          // 忽略错误
        }
      };

      window.addEventListener('beforeunload', beforeUnloadHandler);

      // 清理函数：关闭弹窗或组件卸载时清理超时与事件，并尝试解锁
      return () => {
        if (lockTimeoutRef.current) {
          clearTimeout(lockTimeoutRef.current);
          lockTimeoutRef.current = null;
        }
        window.removeEventListener('beforeunload', beforeUnloadHandler);
        if (current?.id && !hasUnlockedRef.current) {
          delockShortItem(current.id);
          hasUnlockedRef.current = true;
        }
      };
    }

    // 当弹窗关闭时，确保清理定时器
    return () => {
      if (lockTimeoutRef.current) {
        clearTimeout(lockTimeoutRef.current);
        lockTimeoutRef.current = null;
      }
    };
  }, [open, current?.id]);

  const showEditModal = (item: any) => {
    // 先判断是否在锁状态
    getLockitem(item?.id).then(res => {
      // 没有加锁的情况打开并加锁
      if (!res?.is_locked) {
        // 加锁
        lockitem({ id: item?.id, lock_duration_minutes: 1 }).then(response => {
          setVisible(true);
          setCurrent(item);
        })
      } else {
        message.warning(res?.message || '当前分镜已被其他人打开')
      }
    })
  };

  const handleDone = () => {
    current?.id && delockShortItem(current?.id)
    setVisible(false);
    setCurrent(null);
  };

  const handleSubmit = (values: any, isEdit: boolean) => {
    if (isEdit) {
      editItem({ ...values, id: current?.id }).then(res => {
        setVisible(false);
        delockShortItem(current?.id)
        run({ project_id: id });
      })
    } else {
      const curdata = {
        ...values,
        project_id: id,
      }
      addItem(curdata)
    }
  };

  const removeList = (item: any) => {
    Modal.confirm({
      title: '是否确认删除？',
      onOk: () => {
        getLockitem(item?.id).then(res => {
          // 没有加锁的情况打开并加锁
          if (!res?.is_locked) {
            // 加锁
            lockitem({ id: item?.id, lock_duration_minutes: 1 }).then(response => {
              delItem(item?.id)
            })
          } else {
            message.warning(res?.message || '当前分镜已被其他人打开')
          }
        })
      }
    })
  }

  const nullData: Partial<CardListItemDataType> = {};

  return (
    <PageContainer
      extra={<Button onClick={() => history.push('/dashboard')}>返回</Button>}>
      <div style={{ display: 'flex' }}>
        <div style={{ flex: 1 }}>
          <Suspense fallback={<PageLoading />}>
            <IntroduceRow data={summaryData} loading={summaryLoading} />
          </Suspense>
          <Card title="分镜序列">
            <div className={styles.cardList}>
              <List<Partial<CardListItemDataType>>
                rowKey="project_id"
                loading={loading}
                grid={{
                  gutter: 16,
                  xs: 1,
                  sm: 2,
                  md: 3,
                  lg: 3,
                  xl: 4,
                  xxl: 4,
                }}
                dataSource={[nullData, ...data]}
                renderItem={(item, index) => {
                  if (item?.project_id) {
                    return (
                      <List.Item key={item.project_id}>
                        <Card
                          className={styles.card}
                          title={
                            <div className={styles.card_title_wrap}>
                              <div className={styles.card_title_wrap_left}>
                                <div className={styles.card_title_wrap_left_idx}>{item?.shot_number}</div>
                                <div>分镜</div>
                              </div>
                              <div className={styles.card_title_wrap_right}>{item?.duration} 秒</div>
                            </div>
                          }
                          actions={[
                            <EditOutlined key="edit" onClick={() => showEditModal(item)} />,
                            <DeleteOutlined key="ellipsis" onClick={() => removeList(item)} />,
                          ]}
                        >
                          <Card.Meta
                            // title={
                            //   <div>
                            //     <Tag color="magenta">magenta</Tag>
                            //     {/* <Tag color="red">red</Tag>
                            // <Tag color="volcano">volcano</Tag>
                            // <Tag color="orange">orange</Tag> */}
                            //     <Tag color="gold">gold</Tag>
                            //     <Tag color="lime">lime</Tag>
                            //     {/* <Tag color="green">green</Tag>
                            // <Tag color="cyan">cyan</Tag>
                            // <Tag color="blue">blue</Tag>
                            // <Tag color="geekblue">geekblue</Tag>
                            // <Tag color="purple">purple</Tag> */}
                            //   </div>
                            // }
                            description={
                              <Paragraph
                                className={styles.item}
                                ellipsis={{
                                  rows: 3,
                                }}
                              >
                                {item.content}
                              </Paragraph>
                            }

                          />
                        </Card>
                      </List.Item>
                    );
                  }
                  return (
                    <List.Item>
                      <Button type="dashed" className={styles.newButton} onClick={() => setVisible(true)}>
                        <PlusOutlined /> 新增分镜
                      </Button>
                    </List.Item>
                  );
                }}
              />
            </div>
          </Card>
          <OperationModal
            open={open}
            current={current}
            onDone={handleDone}
            onSubmit={handleSubmit}
          />
        </div>
      </div>
    </PageContainer>
  );
};
export default CardList;
